//
//  MarketViewController.swift
//  iModern
//
//  Created by Ralf on 7/21/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class MarketViewController: TableViewController
{
    let appDelegate        = UIApplication.sharedApplication().delegate as! AppDelegate
    let screen             = UIScreen.mainScreen().bounds
    var articles           = NSMutableDictionary()
    let advertisingManager = AdvertisingManager()
    let activityManager    = ActivityManager()
    
    var max        = 0
    var offset     = 0
    var end        = false
    var activities = NSMutableArray()
    var searchButton: UIBarButtonItem?
    //    var postButton:   UIBarButtonItem?
    var serviceCategoriesChooseButton:   UIBarButtonItem?
    var serviceCategories:               String?
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh:", name: "Refresh Market", object: nil)
        
        
        self.tableView.registerNib(UINib(nibName: "ActivityViewArticleCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ARTICLE")
        self.tableView.registerNib(UINib(nibName: "ActivityViewAdvertisingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ADVERTISING")
        //        self.tableView.registerNib(UINib(nibName: "ActivityViewTaskCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "TASK")
        self.navigationItem.rightBarButtonItem = nil
    }
    
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }
    
    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated);
        MobClick.beginLogPageView("MarketView")
        appDelegate.rootController.navigationItem.leftBarButtonItem = nil
        appDelegate.rootController.navigationItem.titleView = nil
        appDelegate.rootController.navigationItem.title = "广场"
        
        initSearchButton()
        //        initServiceCategoriesChooseButton()
        
        if activities.count <= 0
        {
            loadData()
        }
    }
    
    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated);
        MobClick.endLogPageView("MarketView")
    }
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return activities.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var cell: UITableViewCell?
        
        let index    = indexPath.row
        let activity = activities[index] as! NSMutableDictionary
        let article  = activity["article"] as! NSMutableDictionary
        let type     = article["type"] as! String
        //        println(data["id"])
        if type == "Advertising"
        {
            let advertisingCell = tableView.dequeueReusableCellWithIdentifier("ADVERTISING", forIndexPath: indexPath) as! ActivityViewAdvertisingCell
            advertisingCell.setData(activity)
            cell = advertisingCell
            
        }
        else
        {
            let articleCell = tableView.dequeueReusableCellWithIdentifier("ARTICLE", forIndexPath: indexPath) as! ActivityViewArticleCell
            articleCell.setData(activity)
            cell = articleCell
        }
        return cell!
    }
    
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
    }
    */
    
    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
    // Delete the row from the data source
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    }
    */
    
    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
    
    }
    */
    
    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the item to be re-orderable.
    return true
    }
    */
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        let screen = UIScreen.mainScreen().bounds
        
        let message       = activities.objectAtIndex(indexPath.row).objectForKey("article")?.objectForKey("message") as! NSString
        let messageHeight = sizeOfText(message).height
        return screen.size.width + 70 + messageHeight + 50
    }
    
    func initServiceCategoriesChooseButton()
    {
        //临时屏蔽分类选择button
        return
        /*
        if serviceCategoriesChooseButton == nil
        {
            serviceCategoriesChooseButton = UIBarButtonItem(image: UIImage(named: "ServiceCategories-Small.png")!.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "filterByServiceCategories:")
        }
        
        appDelegate.rootController.navigationItem.rightBarButtonItem = serviceCategoriesChooseButton
        */
    }
    
    func initSearchButton()
    {
        if searchButton == nil
        {
            let image = UIImage(named: "Search-Small.png")!.imageWithRenderingMode(.AlwaysOriginal)
            searchButton = UIBarButtonItem(image: image, style: .Plain, target: self, action: "search:")
        }
        
        appDelegate.rootController.navigationItem.leftBarButtonItem = searchButton;
        appDelegate.rootController.navigationItem.rightBarButtonItem = nil;
    }
    
    @IBAction func segmentSelected(sender: UISegmentedControl)
    {
        reloadData(sender)
    }
    
    //    func getCategories() -> String!
    //    {
    //        return self.activityChannelSegmentedControl!.titleForSegmentAtIndex(self.activityChannelSegmentedControl!.selectedSegmentIndex)!
    //    }
    
    func loadData()
    {
        if serviceCategories == nil || serviceCategories != nil
        {
            let rs = advertisingManager.queryAdvertising(max, offset: offset)
            
            if (rs == nil)
            {
                self.alertNetworkConnectionException()
                return
            }
            
            if (rs!.hasErrors())
            {
                self.alertWarningMessage(rs?.errorMessage)
                return
            }
            
            if (rs!.isEmpty())
            {
                end = true
            }
            else
            {
                for o in rs!.toMutableArray()
                {
                    let activity = o as! NSMutableDictionary
                    let article  = NSMutableDictionary(dictionary: activity["article"] as! NSDictionary)
                    activity["article"] = article
                    activities.addObject(activity)
                    
                }
                //            activities.addObjectsFromArray(rs!.toMutableArray() as [AnyObject])
                offset = activities.count
            }
        }
        //        if serviceCategories != nil
        //        {
        //            var rs: ResultSet?
        //            rs = activityManager.queryByAdvertising(max, offset: offset, tag: serviceCategories)
        //            if (rs == nil)
        //            {
        //                self.alertNetworkConnectionException()
        //                return
        //            }
        //
        //            if (rs!.hasErrors())
        //            {
        //                self.alertWarningMessage(rs?.errorMessage)
        //                return
        //            }
        //
        //            if (rs!.isEmpty())
        //            {
        //                end = true
        //            }
        //            else
        //            {
        //                activities.addObjectsFromArray(rs!.toMutableArray() as [AnyObject])
        //                offset = activities.count
        //            }
        //        }
        
        self.tableView.reloadData()
    }
    
    @IBAction override func reloadData(sender: AnyObject!)
    {
        offset = 0
        end = false
        activities.removeAllObjects()
        loadData()
        
        super.reloadData(sender)
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        let activity = activities[indexPath.row] as! NSMutableDictionary
        //        println(activity)
        let article = activity["article"] as! NSDictionary
        let type    = article["type"] as! String
        
        if type == "Article"
        {
            let controller = ArticlePageViewController()
            controller.activity = activity
            self.pushViewController(controller)
        }
        else
        {
            let controller = AdvertisingPageViewController()
            controller.activity = activity
            self.pushViewController(controller)
        }
    }
    
    @IBAction func search(sender: AnyObject)
    {
        let controller = ActivitySearchViewController()
        self.pushViewController(controller)
    }
    
    @IBAction func refresh(sender: AnyObject)
    {
        self.reloadData(sender)
        self.tableView.reloadData()
    }
    
    func sizeOfText(text: NSString) -> CGSize
    {
        let paragraphStyle = NSMutableParagraphStyle()
        
        paragraphStyle.lineHeightMultiple = 16
        paragraphStyle.maximumLineHeight = 20
        paragraphStyle.minimumLineHeight = 20
        
        //        paragraphStyle.firstLineHeadIndent = 20
        paragraphStyle.alignment = .Left
        
        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14),
            NSParagraphStyleAttributeName: paragraphStyle,
            NSForegroundColorAttributeName: UIColor.darkGrayColor()]
        
        let frame = CGSizeMake(screen.size.width, screen.size.height)
        let options = unsafeBitCast(NSStringDrawingOptions.TruncatesLastVisibleLine.rawValue|NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue |
            NSStringDrawingOptions.UsesFontLeading.rawValue,
            NSStringDrawingOptions.self)
        let size  = text.boundingRectWithSize(frame, options: options, attributes: attributes, context: nil)
        return size.size
    }
    
    @IBAction func loadCreateArticleViewController(sender: AnyObject)
    {
        let controller = CreateContentViewController()
        controller.contentType = "Article";
        pushViewController(controller)
    }
    
    @IBAction func filterByServiceCategories(sender: AnyObject)
    {
        let controller = ServiceCategoriesViewController()
        //        let controller = CategoryViewController()
        controller.activityViewController = self
        self.pushViewController(controller)
    }
    
}
